from Acquisition import aq_parent, aq_inner
from zope.interface import implements
from zope.component import getMultiAdapter
from zope.component import getUtility
from Products.CMFCore.utils import getToolByName
from Products.CMFCore.interfaces import ISiteRoot
from Products.CMFCore.interfaces import IContentish
from Products.CMFCore.permissions import ManagePortal
from zope.app.publisher.browser.menu import BrowserMenu
from zope.app.publisher.browser.menu import BrowserSubMenuItem

from plone.app.multilingual import MultilingualMessageFactory as _
from plone.app.multilingual.translation import NotTranslatable
from plone.app.multilingual.browser.interfaces import ITranslateMenu
from plone.app.multilingual.browser.interfaces import ITranslateSubMenuItem
from plone.app.multilingual.interfaces import ITranslatable
from plone.app.multilingual.interfaces import ITranslationGroupLookup, ITranslationUtility

from plone.memoize.instance import memoize


class TranslateMenu(BrowserMenu):
    implements(ITranslateMenu)

    def getUntranslatedLanguages(self, context):
        languageconf = getToolByName(context,'portal_languages')
        languages = languageconf.supported_langs
        translated = []
        # Check if it can be translated
        if ITranslatable.providedBy(context):
            try:
                translationgroup = ITranslationGroupLookup(context).getTranslationGroup()
                translated = translationgroup.getTranslationLanguages()
            except NotTranslatable, e:
                # We can't translate this object
                languages = []
                pass
            except:
                raise
        else:
            # We can't translate this object
            languages = []
        languages=[lang for lang in languages if lang not in translated]
        languages.sort(key=lambda x: x[1])
        return languages


    def getMenuItems(self, context, request):
        """Return menu item entries in a TAL-friendly form."""
        menu=[]
        url=context.absolute_url()
        lt=getToolByName(context, "portal_languages")
        ptool = getToolByName(context, "portal_properties").multilingual_properties
        showflags=lt.showFlags()
        context_state=getMultiAdapter((context, request),
                name="plone_context_state")

        # see if this item can be translated        
        types = ptool.supported_types
        

            
        langs=self.getUntranslatedLanguages(context)

            
        langsdict = lt.getAvailableLanguageInformation()
        for lang_id in langs:
            lang_name = langsdict[lang_id]['name']
            icon=showflags and lt.getFlagForLanguageCode(lang_id) or None
            item={
                "title"       : lang_name,
                "description" : _(u"title_translate_into",
                                    default=u"Translate into ${lang_name}",
                                    mapping={"lang_name" : lang_name}),
                "action"      : url+"/@@translate?newlanguage=%s" % lang_id,
                "selected"    : False,
                "icon"        : icon,
                "extra"       : { "id"        : "translate_into_%s" % lang_id,
                                  "separator" : None,
                                  "class"     : "",
                                 },
                "submenu"     : None,
                }

            menu.append(item)

        menu.append({
            "title"       : _(u"label_manage_translations",
                                default=u"Manage translations..."),
            "description" : _(u"title_manage_translations",
                                default=u""),
            "action"      : url+"/manage_translations_form",
            "selected"    : False,
            "icon"        : None,
            "extra"       : { "id"        : "_manage_translations",
                              "separator" : langs and "actionSeparator" or None,
                              "class"     : ""
                             },
            "submenu"     : None,
            })


        return menu


class TranslateSubMenuItem(BrowserSubMenuItem):
    implements(ITranslateSubMenuItem)

    title = _(u"label_translate_menu", default=u"Translate into...")
    description = _(u"title_translate_menu",
            default="Manage translations for your content.")
    submenuId = "plone_contentmenu_translate"

    order = 5
    extra = { "id" : "plone-contentmenu-translate" }

    @property
    def action(self):
        return self.context.absolute_url() + "/manage_translations_form"

    def available(self):
        ptool = getToolByName(self.context, "portal_properties")
        if not getattr(ptool,'multilingual_properties',False):
            return False
        types = ptool.multilingual_properties.supported_types
        if not ITranslatable.providedBy(self.context) or  not self.context.portal_type in types:
            return False
        qi=getToolByName(self.context, "portal_quickinstaller");
        return qi.isProductInstalled("plone.app.multilingual")


    def disabled(self):
        return False


    def selected(self):
        return False
        
        

